package com.yobol.jgrowth.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;

/**
 * File upload and download
 *
 * @author
 * @create 2018-04-02 13:26
 **/

@Controller
@RequestMapping(value = "/files")
public class FileController {

    @Value(value = "${ckeditor.storage.image.path}")
    private String ckeditorStorageImagePath;
    @Value(value = "${ckeditor.access.image.url}")
    private String ckeditorAccessImageUrl;

    @RequestMapping(value = "/upload/image",method = {RequestMethod.POST,RequestMethod.GET})
    public void uploadImage(@RequestParam("upload")MultipartFile file, HttpServletRequest request, HttpServletResponse response){
        String username = (String) request.getSession().getAttribute("username");
        String type = "images";
        String imageType = request.getParameter("imageType");

        if (username == null || username.equals("null")){
            return;
        }
        if (!file.isEmpty()){
            try{
                response.setContentType("text/html;charset=UTF-8");
                response.setHeader("Cache-Control","no-cache");
                //解决跨域问题
                //Refused to display 'http://localhost:8080/files/upload/image?CKEditor=practice_content&CKEditorFuncNum=1&langCode=zh-cn' in a frame because it set 'X-Frame-Options' to 'DENY'.
                response.setHeader("X-Frame-Options", "SAMEORIGIN");
                PrintWriter out = response.getWriter();

                String fileName = file.getOriginalFilename();//get filename
                //handle file format error
                String[] temp = fileName.split("\\.");
                if (temp.length > 1){
                    String fileSuffix = temp[temp.length - 1];
                    if (fileSuffix.equals("jpg") || fileSuffix.equals("png") || fileSuffix.equals("jpeg") || fileSuffix.equals("gif") || fileSuffix.equals("bmp")){
                        File folder = chooseFolder(ckeditorStorageImagePath,type,username,imageType);
                        if (folder == null){
                            return;
                        }

                        //将文件写入本地
                        File newFile = new File(folder,fileName);
                        byte[] bytes = file.getBytes();
                        BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(newFile));
                        outputStream.write(bytes);
                        outputStream.close();
                        System.out.println("Upload successfully");

                        //返回图片url
                        String fileUrl = ckeditorAccessImageUrl + "/" + type +  "/" + username + "/" + imageType + "/" + newFile.getName();
                        String callback = request.getParameter("CKEditorFuncNum");
                        String script = "<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction(" + callback + ",'" + fileUrl + "');    </script>";
                        out.println(script);
                        out.flush();
                        out.close();
                    } else {
                        System.out.println("Incorrect file format of uploaded file");
                        return;
                    }
                }


            } catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    private File chooseFolder(String root, String type, String username,String imageType){
        String folderPath = root + File.separator + type + File.separator + username + File.separator + imageType;
        File folder = new File(folderPath);
        if (!folder.exists()){
            if (!folder.mkdirs()){
                System.out.println("Folder fail to create!");
                return null;
            }
        }
        return folder;
    }
}
